<?php

namespace app\api\logic;

use app\common\model\AiOrder;
use app\common\model\OrderOrder;
use app\common\model\OrderOther;
use app\common\model\OrderProject;
use app\common\model\User;
use think\db\Query;
use think\Exception;
use think\facade\Db;

class OrderLogic
{
    public static function create($data)
    {
        $user = User::where('id',$data['user_id'])->find();
        if ($user) {
            $size = [
                1 => "1024*1024",
                2 => "720*1280",
                3 => "1280*720"
            ];
            Db::startTrans();
            try {
                $cost = $data['n'] * 2;
                if ($user->xianqi < $cost) {
                    throwError('仙气不足');
                }
                $user->xianqi -= $cost;
                $user->save();
                $order = AiOrder::create([
                    "user_id" => $data['user_id'],
                    "n" => $data['n'],
                    "prompt" => $data['prompt'],
                    "size" => $size[$data['size']] ?? '720*1280',
                    "type" => $data['type'],
                ]);
                Db::commit();
                queue('app\common\job\AiOrder@create',$order->id,0,'create');
                return $order;
            } catch (Exception $exception) {
                Db::rollback();
                throwError($exception->getMessage());
            }
        }
        throwError('用户不存在');
    }

    public static function getDetail($id)
    {
        $order = AiOrder::where('id',$id)
            ->with(['image'=>function(Query $query) {
                $query->where('store_type','public')->where('is_open',1);
            }])
            ->find();
        return $order;
    }
}